package sunwin.yoms.web.controller.resource;

import jodd.datetime.JDateTime;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.comm.LogConst;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsFunction;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.comm.model.NameAndValueModel;
import sunwin.yoms.comm.model.TimeSpan;
import sunwin.yoms.domain.person.UserDomain;
import sunwin.yoms.domain.resource.StadiumDomain;
import sunwin.yoms.service.person.UserService;
import sunwin.yoms.service.resource.SubscribeOrderService;
import sunwin.yoms.service.rmiServer.ISubscribeOrder;
import sunwin.yoms.web.comm.R;
import sunwin.yoms.web.comm.YomsAjaxAnswer;
import sunwin.yoms.web.comm.YomsController;
import sunwin.yoms.web.comm.YomsControllerDefaultData;
import sunwin.yoms.web.comm.resolverArg.YomsDateParam;
import sunwin.yoms.web.comm.resolverArg.YomsTimeParam;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by watson on 2015/10/19.
 */
@Controller
public class SubscriptionContoller {
    @Autowired
    private SubscribeOrderService subscribeOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private YomsControllerDefaultData defaultData;
    @Autowired
    ISubscribeOrder iSubscribeOrder;

    private final String SubscriptionUvm = "resource/subscription.find";
    private final String SubscriptionDetail = "resource/subscription.detail";

    /**
     * 显示用户列表
     */
    @RequestMapping(value = R.SubscriptionUvm, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.SubscriptionUvm, viewName = SubscriptionUvm)
    public ModelAndView showUserDomain(UserDomain userDomain,
                                       @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                       @YomsDateParam JDateTime startTime,
                                       @YomsDateParam JDateTime endTime,
                                       ModelMap modelMap
    ) throws YomsException {
        modelMap.addAttribute("userDomain", userDomain);
        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageIndex(pageIndex);
        Date date1 = startTime == null ? null : startTime.convertToDate();
        Date date2 = startTime == null ? null : endTime.convertToDate();
        List<UserDomain> domains = userService.findUser(userDomain, yomsPage, date1, date2);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", domains);
        mav.addObject("yomsPage", yomsPage);
        return mav;
    }

    /**
     * 根据用户ID来查询场馆
     */
    @RequestMapping(value = R.SubscriptionDetail, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.SubscriptionDetail, viewName = SubscriptionDetail)
    public void initSubscriptionStadium(ModelMap modelMap,
                                        @RequestParam(required = false, defaultValue = "1")
                                        int pageIndex,
                                        int id) throws YomsException {
        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageSize(4);
        yomsPage.setPageIndex(pageIndex);
        List<StadiumDomain> stadiumDomains = subscribeOrderService.getSubscribeStadiumsByUid(id, yomsPage);
        modelMap.addAttribute("page", yomsPage);
        modelMap.addAttribute("stadiumDomains", stadiumDomains);
        //modelMap传递参数
        modelMap.addAttribute("uid", id);
    }

    /**
     * 根据场馆ID查询预约日期
     */
    @RequestMapping(value = R.SubscribeDateById, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getSubscribeDateByUidWithSid(int uid, int sid) {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        try {
            List<JDateTime> dateTimes = subscribeOrderService.getSubscribeDateByUidWithSid(uid, sid);
            List<String> dateStrings = new ArrayList<>();
            for (JDateTime date : dateTimes) {
                dateStrings.add(date.toString("YYYY-MM-DD"));
            }
            answer.setExceptions(dateStrings);
        } catch (YomsException e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);

        return jsonObject.toString();

    }

    /**
     * 根据场馆日期查询预约时间段
     */
    @RequestMapping(value = R.SubscribeTimeSpanById, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getSubscribeTimeSpanByUidWithSidWithDate(int uid, int sid, @YomsDateParam JDateTime date) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        try {
            List<TimeSpan> timeSpans = subscribeOrderService.getSubscribeDateTimeSpanByUidWithSidWithDate(uid, sid, date);
            List<NameAndValueModel> nameAndValueModels = new ArrayList<>();
            for (TimeSpan timeSpan : timeSpans) {
                NameAndValueModel navm = new NameAndValueModel();
                navm.setName(timeSpan.getStartTimeString());
                navm.setValue(timeSpan.getEndTimeString());
                nameAndValueModels.add(navm);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(nameAndValueModels);

            answer.setData(jsonArray.toString());
        } catch (YomsException e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);

        return jsonObject.toString();
    }

    /**
     * 按时间段取消预约类型
     */
    @RequestMapping(value = R.SubscribeCancelByTime, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object CancelSubByTime(int uid, int sid, @YomsDateParam JDateTime date, @YomsTimeParam Time startTime, @YomsTimeParam Time endTime) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        Date date1 = date == null ? null : date.convertToDate();
        Time time1 = startTime == null ? null : startTime;
        Time time2 = endTime == null ? null : endTime;
        TimeSpan timeSpan = new TimeSpan();
        timeSpan.setStartTime(time1);
        timeSpan.setEndTime(time2);
        //传入时间转为long格式
        List<TimeSpan> timeSpans = new ArrayList<>();
        timeSpans.add(timeSpan);
        long timeSpanLong = subscribeOrderService.convertTimeSpansToLong(timeSpans);
        try {
            //同步远程删除预约。
            iSubscribeOrder.cancelSubscribe(uid, sid, date1, timeSpanLong);
            //本地删除预约
            //subscribeOrderService.cancelSubscribe(sid, date1, timeSpanLong);
        } catch (Exception e) {
            Logger.getLogger(LogConst.SUNWIN).error(e);
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject.toString();
    }

    /**
     * 取消天类型预约
     */
    @RequestMapping(value = R.SubscribeCancelById, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object CancelSube(int uid, int sid, @YomsDateParam JDateTime date) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        try {
            iSubscribeOrder.cancelSubscribeDay(uid, sid, date);
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject.toString();
    }

    /**
     * 批量取消预约
     */
    @RequestMapping(value = R.SubscribeCancelBatch, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object CancelSubBatch(int uid, int sid, @YomsDateParam JDateTime startDate, @YomsDateParam JDateTime endDate) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        try {
            iSubscribeOrder.batchCancelSubscribe(uid, sid, startDate, endDate);
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject.toString();
    }

}
